/*
 * sound.c
 *
 *  Created on: Mar 16, 2011
 *      Author: Sharks Group
 */

#include "../sound/soundheader.h"
#include "../sound/dead.c"
#include"../common/sgba.h"

#define MULTIBOOT int __gba_multiboot;
MULTIBOOT

u16 SampleLength = 0;
u16 SamplePosition;

typedef struct tagSound {
	void *pBuffer;
	u16 samplerate;
	u32 length;
}sound;

sound soundDead = {&dead, 44100, 15008};

void PlaySound(sound *theSound) {
	u16 samples;
	//output to both channels and reset the FIFO
	REG_SGCNT0_H = DSOUND_A_RIGHT_CHANNEL | DSOUND_A_LEFT_CHANNEL
			| DSOUND_A_FIFO_RESET;
	//enable all sound
	REG_SGCNT1 = SOUND_MASTER_ENABLE;
	//DMA1 source address
	REG_DMA1SAD = (u32) theSound->pBuffer;
	//DMA1 destination address
	REG_DMA1DAD = 0x40000A0;
	//write 32 bits into destination every vblank
	REG_DMA1CNT_H = DMA_DEST_FIXED | DMA_REPEAT | DMA_32
			| DMA_TIMING_SYNC_TO_DISPLAY | DMA_ENABLE;
	samples = 16777216 / theSound->samplerate; //2097
	REG_TM0D = 65536 - samples;

	SampleLength = theSound->length / samples * 15.57;
	SamplePosition = 0;
	REG_TM0CNT = TIMER_ENABLE;
}

void channelSound(void){
//Play a sound on channel 1
	REG_SOUNDCNT_X = 0x80;
	//full volume, enable sound 2 to left and right
	REG_SOUNDCNT_L=0x2277;
	// Overall output ratio - Full
	REG_SOUNDCNT_H = 2;

	REG_SOUND2CNT_L=0x7400; //duty=50%,envelope decrement
	REG_SOUND2CNT_H=0x8400; //frequency=0x0400, loop mode
}
